package com.open.capacity.user.service.impl;

import com.open.capacity.common.model.RoleTitle;
import com.open.capacity.common.model.Title;
import com.open.capacity.common.model.UserTitle;
import com.open.capacity.common.util.PageUtil;
import com.open.capacity.common.web.PageResult;
import com.open.capacity.common.web.Result;
import com.open.capacity.user.dao.TitleDao;
import com.open.capacity.user.service.TitleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

/**
 * 称号实现层
 * @author liutao
 * @date 2021-02-01 16:52
 */
@Service
public class TitleServiceImpl implements TitleService {

    @Autowired
    private TitleDao titleDao;

    // 模糊查询称号
    @Override
    public PageResult<Title> getSelectTitles(Map<String, Object> params) {
        int count = titleDao.count(params);
        PageUtil.pageParamConver(params,true);
        List<Title> titles = titleDao.getSelectTitles(params);
        return PageResult.<Title>builder().code(0).
                data(titles).count((long) count).build();
    }

    // 添加称号
    @Override
    @Transactional
    public Result addTitle(Title title) {
        boolean isHave = isHaveTitle(title.getTtname());
        if (isHave){
            int result = titleDao.addTitle(title);
            if (result > 0 && title.getTttype() == 1){
                RoleTitle roleTitle = RoleTitle.builder()
                        .titlid(title.getTitlid())
                        .roleid(title.getRoleid()).build();
                int rotlid = titleDao.addRoleTitle(roleTitle);
            }
            return Result.succeed(result == 1?"添加成功":"添加失败");
        }
        return Result.failed("该称号已存在");
    }

    // 修改称号
    @Override
    public Result updateTitle(Title title) {
        int result = titleDao.updateTitle(title);
        return Result.succeed(result == 1 ? "修改成功" : "修改失败");
    }

    // 删除称号
    @Override
    public Result delTitle(int titlid) {
        int result = titleDao.delTitle(titlid);
        return Result.succeed(result > 0?"删除成功":"删除失败");
    }

    @Override
    public PageResult getTitleByUserId(Map<String, Object> params) {
        int count = titleDao.countByUserId(params);
        PageUtil.pageParamConver(params,true);
        List<Title> titles = titleDao.getTitleByUserId(params);
        return PageResult.<Title>builder().code(0).
                data(titles).count((long) count).build();
    }

    // 判断称号是否存在
    private boolean isHaveTitle(String ttname) {
        List<Title> list = titleDao.isHaveTitle(ttname);
        return list.size() == 0?true:false;
    }


}
